package mini.ideashare.cms.controller;

import com.alibaba.fastjson.JSON;
import mini.ideashare.cms.base.BaseResponse;
import mini.ideashare.cms.base.PageData;
import mini.ideashare.cms.manager.CategoryManager;
import mini.ideashare.cms.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lixiang
 * @CreateTime 2018/10/27
 **/
@Controller
public class CategoryController extends AbstractBaseController {
    @Autowired
    private CategoryManager categoryManager;

    @GetMapping("/category/query")
    @ResponseBody
    public BaseResponse<PageData<Category>> queryCategory(Category category, Integer pageIndex , Integer pageSize){

        List<Category> categories = categoryManager.queryCategory(category, pageIndex, pageSize);
        Long totalCount = categoryManager.countCategory(category);

        pageIndex = pageIndex == null?0:pageIndex;
        pageSize = pageSize == null?0:pageSize;
        return  BaseResponse.assemblePageResponse(categories,totalCount,pageIndex,pageSize);
    }

    @PostMapping("/category/save")
    @ResponseBody
    public BaseResponse<String> saveItem(Category category){
        BaseResponse<String> baseResponse = new BaseResponse<>();
        categoryManager.saveCategory(category);
        baseResponse.setData("OK");
        return  baseResponse;
    }

    @GetMapping("/category/list")
    @ResponseBody
    public String listItem(Category category, Integer pageNumber , Integer pageSize){

        Map<String,Object> map  = new HashMap<>();

        List<Category> categories = categoryManager.queryCategory(category, pageNumber, pageSize);
        Long totalCount = categoryManager.countCategory(category);
        map.put("total",totalCount);
        map.put("rows",categories);
        return JSON.toJSONString(map);
    }

    @GetMapping("/category/delete")
    @ResponseBody
    public String delete(Long id){
        categoryManager.deleteCategory(id);
        return "OK";
    }

}
